package com.cxs.musicplaywidget.view;

import com.cxs.musicplaywidget.MainAbility;
import com.cxs.musicplaywidget.ResourceTable;
import com.cxs.musicplaywidget.commonevent.EventManager;
import com.cxs.musicplaywidget.data.EventParam;
import com.cxs.musicplaywidget.data.MDevice;
import com.cxs.musicplaywidget.player.data.MusicInfo;
import com.cxs.musicplaywidget.player.store.ImageStore;
import com.cxs.musicplaywidget.service.DeviceManager;
import com.cxs.musicplaywidget.service.ServiceManager;
import com.cxs.musicplaywidget.service.idl.MyAgentProxy;
import com.cxs.musicplaywidget.util.LogUtils;
import com.cxs.musicplaywidget.view.list.ListItemProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.List;

import static com.cxs.musicplaywidget.data.EventParam.EventAction.*;
import static ohos.agp.components.Component.HIDE;
import static ohos.agp.components.Component.VISIBLE;

/**
 * @ClassName AbilityAdapter
 * @Author cxs
 * @Version 1.0
 * @Description 更新Ability视图
 * @Date 2022/03/10
 */
public class AbilityControllerAdapter implements IControllerAdapter {
    private static final String tag = AbilityControllerAdapter.class.getSimpleName();
    private final Context context;
    private final AbilitySlice abilitySlice;
    private final DeviceManager deviceManger;
    private final ServiceManager serviceManager;
    TabList deviceTabList;
    Button btnPlay, btnPause, btnPrevious, btnNext, btnRefresh, btnStartFA;
    Text textLoading;
    ListContainer listContainer;
    ListItemProvider listItemProvider = new ListItemProvider();
    EventHandler mainThread = new EventHandler(EventRunner.getMainEventRunner());
    static long l1;
    static long l3;

    public AbilityControllerAdapter(Context context) {
        LogUtils.debug(tag, "AbilityControllerAdapter()");
        this.context = context;
        this.abilitySlice = (AbilitySlice) context;
        deviceManger = DeviceManager.getInstance(context);
        serviceManager = ServiceManager.getInstance(context);
        initComponent();
        initListener();
    }

    private void initComponent() {
        if (abilitySlice == null) {
            return;
        }
        System.out.println("abilitySlice = " + abilitySlice);
        try {
            deviceTabList = abilitySlice.findComponentById(ResourceTable.Id_device_tab_list);
            listContainer = abilitySlice.findComponentById(ResourceTable.Id_play_list_container);
            btnRefresh = abilitySlice.findComponentById(ResourceTable.Id_btn_refresh);
            btnPlay = abilitySlice.findComponentById(ResourceTable.Id_btn_play);
            btnPause = abilitySlice.findComponentById(ResourceTable.Id_btn_pause);
            btnPrevious = abilitySlice.findComponentById(ResourceTable.Id_btn_previous);
            btnNext = abilitySlice.findComponentById(ResourceTable.Id_btn_next);
            textLoading = abilitySlice.findComponentById(ResourceTable.Id_text_loading);
            btnStartFA = abilitySlice.findComponentById(ResourceTable.Id_btn_start_fa);
        } catch (Exception e) {
            System.out.println("e.getMessage() = " + e.getMessage());
        }

    }

    private void initListener() {
        btnRefresh.setClickedListener(c -> {
            List<MDevice> deviceList = deviceManger.getDeviceList(true);
            if (!deviceList.isEmpty()) {
                EventManager.publishEvent(new EventParam(LOAD_DEVICE_LIST));
                serviceManager.init();
            }
        });
        btnPlay.setClickedListener(c -> {
            deviceManger.getDevice().proxy().start(PLAY);
            deviceManger.getDevice().proxy().start(GET_PLAY_LIST);
        });
        btnPause.setClickedListener(c -> deviceManger.getDevice().proxy().start(PAUSE));
        btnPrevious.setClickedListener(c -> {
            deviceManger.getDevice().proxy().start(PREVIOUS);
            deviceManger.getDevice().proxy().start(GET_PLAY_LIST);
        });
        btnNext.setClickedListener(c -> {
            deviceManger.getDevice().proxy().start(NEXT);
            deviceManger.getDevice().proxy().start(GET_PLAY_LIST);
        });
//        btnStartFA.setClickedListener(c -> {
//            startFA(deviceManger.getDevice().getDeviceId());
//        });
    }

    private void startFA(String deviceId) {
        if (deviceId.equals("")) {
            return;
        }
        Intent intent = new Intent();
        Operation build = new Intent.OperationBuilder()
                .withDeviceId(deviceId)
                .withBundleName(abilitySlice.getBundleName())
                .withAbilityName(MainAbility.class.getName())
                .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                .build();
        intent.setOperation(build);
        abilitySlice.startAbility(intent, 0);
    }

    @Override
    public boolean isConnected(byte deviceIndex) {
        return false;
    }

    @Override
    public void updateDeviceList(boolean reload) {
        if (!reload) {
            return;
        }
        byte index = deviceManger.getCurrentIndex();
        List<MDevice> deviceList = deviceManger.getDeviceList();
        if (deviceList == null || deviceList.isEmpty()) {
            return;
        }
        mainThread.postTask(() -> {
            long l = System.currentTimeMillis();
            long l2 = l - l1;
            if (l2 < 50 && deviceTabList.getTabCount() > 0) {
                return;
            }
            deviceTabList.removeAllComponents();
            deviceTabList.release();
            LogUtils.debug(tag, "updateDeviceList.deviceList =" + deviceList);
            for (int i = 0; i < deviceList.size(); i++) {
                TabList.Tab tab = deviceTabList.new Tab(abilitySlice);
                LogUtils.debug(tag, "updateDeviceList.i =" + i);
                LogUtils.debug(tag, "updateDeviceList.deviceList.get(i) =" + deviceList.get(i));
                tab.setText(deviceList.get(i).getName());
                if (index == i) {
                    deviceTabList.addTab(tab, true);
                } else {
                    deviceTabList.addTab(tab, false);
                }
            }
            deviceTabList.addTabSelectedListener(new TabList.TabSelectedListener() {
                @Override
                public void onSelected(TabList.Tab tab) {
                    LogUtils.debug(tag, "onSelected.tab = " +tab.getPosition());
                    byte deviceIndex = (byte) tab.getPosition();
                    boolean connected = serviceManager.connectService(deviceIndex);
                }
                @Override
                public void onUnselected(TabList.Tab tab) {}
                @Override
                public void onReselected(TabList.Tab tab) {}
            });
            l1 = System.currentTimeMillis();

        });
    }

    @Override
    public void updatePlayerControl(EventParam.PlayerState playerState) {
        LogUtils.debug(tag, "updatePlayerControl.playerState=" + playerState);
        mainThread.postTask(() -> {
            switch (playerState) {
                case NONE: {
                    listContainer.setVisibility(HIDE);
                    textLoading.setVisibility(VISIBLE);
                    break;
                }
                case PLAYING: {
                    btnPlay.setVisibility(HIDE);
                    btnPause.setVisibility(VISIBLE);
                    break;
                }
                case PREPARED:
                case PAUSED: {
                    btnPlay.setVisibility(VISIBLE);
                    btnPause.setVisibility(HIDE);
                    listContainer.setVisibility(VISIBLE);
                    textLoading.setVisibility(HIDE);
                    break;
                }
            }
        });
    }

    @Override
    public void updatePlaylist(EventParam eventParam) {
        List<MusicInfo> playList = eventParam.getPlayList();
        int playIndex = eventParam.getPlayIndex();
        LogUtils.debug(tag, "updatePlaylist.playList =" + playList);
        if (playList == null) {
            deviceManger.getDevice().proxy().getPlayList();
            return;
        }
        mainThread.postTask(() -> {
            long l = System.currentTimeMillis();
            long l4 = l - l3;
            System.out.println("差值 = " + l4);
            if (l4 < 500 && listItemProvider.getCount() > 0) {
                return;
            }
            System.out.println("差值 l4 = " + l4);
            listItemProvider.setPlayList(playList, playIndex);
            listContainer.setItemProvider(listItemProvider);
            listContainer.setItemClickedListener((container, component, position, id) -> {
                MusicInfo musicInfo = (MusicInfo) listContainer.getItemProvider().getItem(position);
                LogUtils.debug(tag, "updatePlaylist.musicInfo =" + musicInfo);
                MyAgentProxy proxy = deviceManger.getDevice().proxy();
                proxy.addEvent(new EventParam(PLAY, musicInfo.getIndex()));
                proxy.addEvent(new EventParam(GET_PLAY_LIST));
                proxy.start();
            });
            l3 = System.currentTimeMillis();
        });
    }

    @Override
    public void updateMusicInfo(MusicInfo musicInfo) {
//        byte[] thumb = thumbnail;
//        if (thumb == null || thumb.length <= 0) {
//            ImageStore imageStore = ImageStore.getInstance(context);
//            thumb = imageStore.getRotateImage(45);
//        }
//        Image image = abilitySlice.findComponentById(ResourceTable.Id_image_thumbnail);
//        ImageStore imageStore = ImageStore.getInstance(context);
//        abilitySlice.getUITaskDispatcher().asyncDispatch(() -> image.setPixelMap(imageStore.getRotatePixelMap(angle)));
    }

    @Override
    public void updateVolume(int max, int vol) {

    }

    @Override
    public void updateThumbnail(byte[] thumbnail, int index) {

    }
}
